package com.qu.waibao.account;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.baidu.MapActivity;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.bean.UserInfor;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.adapter.GridImageAdapter;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.HttpModeBase;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.ToastUtil;
import com.squareup.haha.perflib.Main;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

public class XiuAuthonticActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.tv_dingwei)
    TextView tv_dingwei;
    @BindView(R.id.et_card)
    EditText et_card;
    private GridImageAdapter imageAdapter;
    private HttpModeBase httpModeBase;
    private String province = "";
    private String city = "";
    private String area = "";
    private String longitude = "";
    private String latitude = "";
    private List<LocalMedia> selectList;
    private UserInfor userInfor;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HttpModeBase.HTTP_SUCCESS:
                    String result = (String) msg.obj;
                    int position = msg.arg2;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if(jsonObject.optInt("status") == 1){
                            String url = jsonObject.optString("src");
                            imageAdapter.addItem(url);
                            if(position < selectList.size() -1) {
                                position++;
                                imageSaveSet(selectList.get(position).getCompressPath(), position);
                            }
                        }else {
                            imageSaveSet(imageAdapter.getItems().get(position),position);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case HttpModeBase.HTTP_ERROR:
                    SimpleHUD.dismiss();
                    break;
            }
        }
    };

    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            userInfor = (UserInfor) bundle.getSerializable("UserInfor");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_xiu_authontic;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("修理工认证");
        tv_sure.setVisibility(View.VISIBLE);
        iv_publish.setVisibility(View.GONE);
        ll_back.setVisibility(View.GONE);
        tv_sure.setText("取消");
        httpModeBase = new HttpModeBase(handler,this);

    }
    @Override
    protected void onResume() {
        super.onResume();
        if(LocationUtils.Mylocation != null){
            province = LocationUtils.Mylocation.getProvince();
            city = LocationUtils.Mylocation.getCity();
            area = LocationUtils.Mylocation.getDistrict();
        }
    }
    @Override
    protected void initData() {
        super.initData();
        //图片
        imageAdapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                if(ContextCompat.checkSelfPermission(XiuAuthonticActivity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                    openPhotos();
                }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(imageAdapter);
        if(userInfor != null){
            et_name.setText(userInfor.getName());
            et_phone.setText(userInfor.getPhone());
            tv_dingwei.setText(userInfor.getAddress());
            et_card.setText(userInfor.getIdcard());
            if(!TextUtils.isEmpty(userInfor.getImgs())){
                String[] images = userInfor.getImgs().split(",");
                imageAdapter.addList(Arrays.asList(images));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                if(selectList != null) {
                    imageSaveSet(selectList.get(0).getCompressPath(),0);
                }
            }else if(requestCode == 0){
                latitude = String.valueOf(data.getDoubleExtra("latitude",0));
                longitude = String.valueOf(data.getDoubleExtra("longitude",0));
                String address = data.getStringExtra("address");
                tv_dingwei.setText(address);
            }
        }
    }
    public void imageSaveSet(String path,int position){
        httpModeBase.xutilsPostList(NetManager.BaseUrl,NetManager.image_save_set(),path,position,
                true);
    }
    /**
     * 打开相册
     */
    public void openPhotos() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(3)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .isGif(false)// 是否显示gif图片
                .compress(true)// 是否压缩 true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @OnClick({R.id.tv_submit,R.id.ll_dingwei,R.id.tv_sure})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_submit:
                String name = et_name.getText().toString();
                String phone = et_phone.getText().toString();
                String card = et_card.getText().toString();
                String address = tv_dingwei.getText().toString();
                String images = getImages();
                if(TextUtils.isEmpty(name)){
                    ToastUtil.show(this,"请输入您的姓名");
                    return;
                }else if(TextUtils.isEmpty(phone)){
                    ToastUtil.show(this,"请输入您的电话");
                    return;
                }else if(TextUtils.isEmpty(card)) {
                    ToastUtil.show(this, "请输入您的身份证号");
                    return;
                }else if(TextUtils.isEmpty(images)){
                    ToastUtil.show(this, "请上传您的资格证书");
                    return;
                }
                renzheng(images,name,address,phone,card);
                break;
            case R.id.ll_dingwei: //定位
                startActivityForResult(new Intent(this, MapActivity.class),0);
                break;
            case R.id.tv_sure:
                onBackPressed();
                break;
        }
    }
    private String getImages(){
        StringBuilder builder = new StringBuilder();
        String uploadImages = "";
        if(imageAdapter != null){
            for(int i = 0;i<imageAdapter.getItems().size();i++){
                builder.append(imageAdapter.getItems().get(i)).append(",");
            }
            String images = builder.toString();
            if(!TextUtils.isEmpty(images)){
                uploadImages = images.substring(0,images.length()-1);
            }
        }
        return uploadImages;
    }
        public void renzheng(String imgs,String name,String address,String phone,String card){
            SimpleHUD.showLoadingMessage(this,"",AppConfig.isCanCancel);
         Map<String,String> map = new HashMap<>();
         map.put("action", ActionUtil.user_plusinfo_set);
         map.put("userid", AppConfig.getString("userid"));
         map.put("name",name);
         map.put("business_main","");
         map.put("business_second","");
         map.put("legalman","");
         map.put("legalpeopletel","");
         map.put("province",province);
         map.put("city",city);
         map.put("area",area);
         map.put("address",address);
         map.put("longitude",longitude);
         map.put("latitude",latitude);
         map.put("linkman","");
         map.put("linktel",phone);
         map.put("idcard",card);
         map.put("imgs",imgs);
         NetManager.getInstance().request(this, map, false, new XnetCallBack() {
             @Override
             public void onSuccess(String result, String msg) {
                 ToastUtil.show(XiuAuthonticActivity.this,msg);
                 startActivity(new Intent(XiuAuthonticActivity.this, MainActivity.class));
                 finish();
             }

             @Override
             public void onError(Throwable ex, boolean isOnCallback) {
                 SimpleHUD.dismiss();
             }

             @Override
             public void onFinished() {
                 SimpleHUD.dismiss();
             }
         });
     }

    @Override
    public void onBackPressed() {
        if(userInfor != null) {
            finish();
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        httpModeBase = null;
        handler = null;
    }
}
